﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AdamDsk
{
    /// <summary>
    /// Interaction logic for NewImageDialog.xaml
    /// </summary>
    public partial class NewImageDialog : Window
    {
        public NewImageDialog()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        public string Path { get; set; }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (txtName.Text != null)
            {
                var size = 160;
                var ext = ".dsk";
                if (radCustom.IsChecked ?? false) size = Math.Min(Convert.ToInt32(txtInput.Text), 65536);
                if (radDDP.IsChecked ?? false)
                {
                    size = 256;
                    ext = ".ddp";
                }
                if (radDSK.IsChecked ?? false)
                {
                    size = 160;
                    ext = ".dsk";
                }
                if (radDS1.IsChecked ?? false)
                {
                    size = 320;
                    ext = ".ds1";
                }
                if (radDS2.IsChecked ?? false)
                {
                    size = 720;
                    ext = ".ds2";
                }
                if (radDS3.IsChecked ?? false)
                {
                    size = 1440;
                    ext = ".ds3";
                }

                var dsk = new DskFile((uint)(size * 1024));
                dsk.Directory.Header = new DirectoryHeader(txtName.Text.Substring(0,Math.Min(txtName.Text.Length, 11)) + "\x3", size);

                //dsk.Directory.Header.DIR_SIZE = Convert.ToByte(cmbDirectoryBlocks.SelectedIndex + 1);
                //if (dsk.Directory.Header.DIR_SIZE == 0) ++dsk.Directory.Header.DIR_SIZE;
                var filename = System.IO.Path.Combine(this.Path, txtName.Text + ext);
                if (File.Exists(filename)) new FileInfo(filename).Delete();
                var stream = File.OpenWrite(filename);
                dsk.SaveFile(stream);
                stream.Close();
                Result = filename;
                DialogResult = true;
                Close();
            }
            else
            {
                MessageBox.Show(this, "You must supply a name before continuing.", "Error", MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);
            }
        }

        public string Result { get; private set; }
    }
}
